package org.rayken.trix;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;

import org.rayken.trix.commons.card.Card;
import org.rayken.trix.commons.game.Game;
import org.rayken.trix.commons.game.Play;
import org.rayken.trix.commons.game.Player;
import org.rayken.trix.commons.game.Run;
import org.rayken.trix.commons.game.RunType;
import org.rayken.trix.commons.game.Trick;

public class Program {

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		PrintStream sysout = System.out;
		
		Random rand = new Random();
		Game game = new Game(new Player("CD"), new Player("Rayken"),
				new Player("S9on"), new Player("Naili"));

		Player player = game.selectRandomPlayer();
		for (int pi = 0; pi < 4; pi++) {
			for (int k = 0; k < RunType.values().length; k++) {

				RunType runType = RunType.values()[k];
				boolean forced = k == RunType.values().length - 1;
				Run run = game.playRun(runType, player, forced);
				System.out.println(run.getType());
				Player currentPlayer = player;

				boolean finished = false;
				while (!finished) {
					Trick trick = run.nextTrick();
					for (int j = 0; j < 4 && !finished; j++) {
						Play play = trick.nextPlay(currentPlayer);
						List<Card> cards = play.getAvailablePlayableCard();
						if (cards.size() > 0) {
							Card cardToPlay = cards.get(rand.nextInt(cards
									.size()));// No AI, hence select a random
												// playable card.
							sysout.println(currentPlayer + " plays\t"
									+ cardToPlay);
							play.playCard(cardToPlay);
							
							
							if (run.isFinished()) {
								finished = true;
							}
						} else {//Happens only in TRIX
							sysout.println("Pass " + currentPlayer);
						}
						if (run.getDeals().get(currentPlayer).size() == 0) {
							sysout.println("  ## No cards left for " + currentPlayer);
						}
						currentPlayer = game.nextPlayer(currentPlayer);
					}
					if (run.getType() != RunType.TRIX){
						Play winningPlay = trick.getWiningPlay();
						sysout.println("Collected by: " + winningPlay.getPlayer() + " with the " + winningPlay.getCard());
					}
					sysout.println();
				}
				sysout.println();
				sysout.println("Chooser : " + player + ", forced : " + forced);
				
				for (Player p : game.getPlayers()) {
					sysout.println(p + "\t" + game.getScores().get(p));
				}
				sysout.println();
				sysout.println("#####");
			}
			player = game.nextPlayer(player);
		}
	}
}
